package org.grow.authfilter.service;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.Collection;

/**
 * @Author: xwg
 * @CreateDate: 21-7-21
 */

@Service
public class NormalAccessDecision implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection)
            throws AccessDeniedException, InsufficientAuthenticationException {

        FilterInvocation fi = (FilterInvocation) o;
        HttpServletRequest request = fi.getRequest();
        Collection<? extends GrantedAuthority> rolesFromUsername = authentication.getAuthorities();
        Collection<ConfigAttribute> rolesFromUrl = collection;
        System.out.println("NormalAccessDecision: rolesFromUsername"+rolesFromUsername);
        System.out.println("NormalAccessDecision: rolesFromUrl"+rolesFromUrl);

        Boolean flag =false;
//        取交集
        for (GrantedAuthority grantedAuthority : rolesFromUsername) {
            String roleName1 = grantedAuthority.getAuthority();
            for (ConfigAttribute attribute : rolesFromUrl) {
                String roleName2 = attribute.getAttribute();

                if (roleName1.equals(roleName2)) {

                    System.out.println("有交集，权限不拦截");
                    flag =true;
                    break;
                }
            }
        }
        if (!flag){
            throw new AccessDeniedException(
                    MessageFormat.format("{0}试图访问{1}，角色无交集，权限不通过",
                            authentication.getName(),
                            request.getRequestURI()));
        }
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
